package com.mdnote.jianzhi_offer.flash_back;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/10/12
 * @description 剑指 Offer 12. 矩阵中的路径
 */
public class Offer12 {


    public static void main(String[] args) {
        Offer12 offer12 = new Offer12();

//        char[][] chars = {
//                {'a', 'b', 'c', 'd'},
//                {'e', 'f', 'h', 'h'},
//                {'i', 'j', 'k', 'l'},
//                {'a', 'e', 'd', 'k'}
//        };

        char[][] chars = {
                {'C', 'A', 'A'},
                {'A', 'A', 'A'},
                {'B', 'C', 'A'},
        };

        System.out.println(offer12.exist(chars, "AAB"));
//        System.out.println(offer12.exist(chars, "abchkl"));
//        System.out.println(offer12.exist(chars, "aeije"));
    }

    private int[] dx = {0, 0, 1, -1};
    private int[] dy = {1, -1, 0, 0};

    public boolean exist(char[][] board, String word) {

        if (word.length() == 0 || board == null || board.length == 0 || board[0].length == 0) {
            return false;
        }
        // dfs
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[i].length; j++) {
                if(word.charAt(0) == board[i][j]) {
                    if (_dfs(0, i, j, board, word)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean _dfs(int level, int row, int column, char[][] board, String word) {
        // Terminator
        if (level + 1 == word.length()) {
            return true;
        }
        // Process
        char tmp = board[row][column];
        board[row][column] = '0';
        // Drill dwon
        for (int i = 0; i < dx.length; i++) {
            if (level + 1 <= word.length() && inBoard(row + dx[i], column + dy[i], board)) {
                if (word.charAt(level + 1) == board[row + dx[i]][column + dy[i]] &&
                        _dfs(level + 1, row + dx[i], column + dy[i], board, word)) {
                    return true;
                }
            }
        }
        // Restore current data
        board[row][column] = tmp;

        return false;
    }

    private boolean inBoard(int row, int column, char[][] board) {
        return row >= 0 && column >= 0 && row < board.length && column < board[0].length;
    }
}
